﻿using UnityEngine;
using Cysharp.Threading.Tasks;
using System.Collections.Generic;
using System;

/// <summary>
/// 游戏构造器用于初始化各个框架类
/// </summary>
public class GameConstructor : USaBehaviour
{
    private static Dictionary<Type, bool> s_ModuleReadyDict = new Dictionary<Type, bool>();
    private static bool ready
    {
        get
        {
            if (s_ModuleReadyDict.Count <= 0) return false;
            foreach (var kvp in s_ModuleReadyDict)
            {
                if (!kvp.Value) return false;
            }
            return true;
        }
    }

    /// <summary>
    /// 等待初始化完成
    /// </summary>
    public static UniTask WaitForReady()
    {
        return UniTask.WaitUntil(() => ready);
    }

    private void Awake()
    {
        InitGameFrame();
    }

    private void InitGameFrame()
    {
        var types = Tools.GetSubClassesOf<GameFrameClassBase>();
        foreach (var type in types)
        {
            s_ModuleReadyDict.Add(type, false);
            var moduleInstance = type.Assembly.CreateInstance(type.FullName) as GameFrameClassBase;
            if (moduleInstance == null)
            {
                Debug.LogError($"GameFrame：{type.Name} 初始化失败，实例生成失败");
                continue;
            }
            StartInitModule(moduleInstance);
            Debug.Log($"GameFrame： {type.Name} 初始化完成");
        }
    }

    private async void StartInitModule(GameFrameClassBase module)
    {
        foreach (var dependence in module.dependences)
        {
            await UniTask.WaitUntil(() => s_ModuleReadyDict.TryGetValue(dependence, out var ready) && ready);
        }
        await module.InitAsync();
        s_ModuleReadyDict[module.GetType()] = true;
    }
}